package com.example.lib_mvp.musicService;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;


import com.example.lib_mvp.Constant;
import com.tjf.lib_utils.EventBusUtils;
import com.tjf.lib_utils.LogsUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {

    public static final String MusicService = "MusicService";


    //用来控制音乐的播放与暂停。系统自带的
    protected MediaPlayer mediaPlayer;

    //定时器
    protected Timer timer;
    int totalDuration;
    //广播管理器
    //用的是 MainActivity中的
//    public static LocalBroadcastManager localBroadcastManager;

    public MusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
//        localBroadcastManager = MainActivity.localBroadcastManager;
    }

    private void createTimer() {
        if (timer == null) {
            timer = new Timer();
            TimerTask timerTask = new TimerTask() { //定时任务
                @Override
                public void run() {
                    //还没有播放器的时候，就直接退出。
                    if (mediaPlayer == null) return;
                    if (!mediaPlayer.isPlaying()) return;
                    //当前进度， mediaPlayer 自带API，获取当前音频播放到哪里了
                    int currentDuration = mediaPlayer.getCurrentPosition();
                    totalDuration = mediaPlayer.getDuration();
                    //携带数据
//                    LogsUtils.i("音频准备发完毕 currentPosition  getDuration==",
//                            currentDuration, totalDuration,
//                            format(currentDuration), format(totalDuration)
//                    );
                    HashMap<String, String> musicTimes = new HashMap<>();
                    musicTimes.put("totalDuration", format(totalDuration));
                    musicTimes.put("totalDurationInt", totalDuration + "");
                    musicTimes.put("currentDurationInt", currentDuration + "");
                    musicTimes.put("currentDuration", format(currentDuration));
                    EventBusUtils.sendEvent(MusicService, musicTimes);
                }
            };
            timer.schedule(timerTask, 100, 1000); // 1ms后，每1000ms执行 一次 TimerTask;
            //总结下来就是，只要有 mediaPlay的存在，就把当前歌曲播放的具体时长 以广播的形式发送，由MainActivity进行捕获与响应
        }
    }

    public void cancelTimer() {
        if (timer != null) {
            timer.purge();
            timer.cancel();
            timer = null;
        }
    }

    private String format(long time) {
        int minute = 0;
        int second = 0;
        minute = (int) (time / (1000 * 60)) % 60;
        second = (int) (time / 1000) % 60;
        return String.format("%02d", minute) + ":" + String.format("%02d", second);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MusicBinder();
    }

    //用来绑定服务，这样可以通过Activity 与服务进行交互了
    public class MusicBinder extends Binder {
        int mMusicIndex = 0;

        public void prepare(String url, int musicIndex) {//String path
            try {
                LogsUtils.i("音频 开始准备===" + url);
                mMusicIndex = musicIndex;
                pausePlay();
                //重置音乐播放器
                mediaPlayer.reset();
                //加载多媒体文件
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
                mediaPlayer.setOnPreparedListener(mp -> {
                    LogsUtils.i("音频准备发完毕 开始播放");
                    createTimer();//添加计时器
                });
                mediaPlayer.setOnCompletionListener(mp -> {
                    LogsUtils.i("音频播放完毕");
                    EventBusUtils.sendEvent(Constant.MusicStatus, "播放完毕");
                });
            } catch (Exception e) {
                e.printStackTrace();
                LogsUtils.i("音频Exception==" + e.getLocalizedMessage());
            }
        }

        public void play(String url, int musicIndex) {//String path
            try {
                mMusicIndex = musicIndex;
                stopPlay();
                //重置音乐播放器
                mediaPlayer.reset();
                //加载多媒体文件
                mediaPlayer.setDataSource(url);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(mp -> {
                    LogsUtils.i("音频准备发完毕 开始播放");
                    createTimer();//添加计时器
                    mp.start();//播放音乐
                });
                mediaPlayer.setOnCompletionListener(mp -> {
                    LogsUtils.i("音频播放完毕");
                    cancelTimer();//添加计时器
                    EventBusUtils.sendEvent(Constant.MusicStatus, "播放完毕");
                });

            } catch (Exception e) {
                e.printStackTrace();
                LogsUtils.i("音频Exception==" + e.getLocalizedMessage());
            }
        }

        public void play(boolean isPlay) {
            if (isPlay) {
                continuePlay();
            } else {
                pausePlay();
            }
        }

        //下面的暂停继续和退出方法全部调用的是MediaPlayer自带的方法
        public void pausePlay() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();//暂停播放音乐
            }
        }

        public void stopPlay() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                cancelTimer();
                mediaPlayer.stop();//停止播放音乐
                mediaPlayer.reset();
            }
        }

        public void continuePlay() {
            if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                mediaPlayer.start();//继续播放音乐
            }
        }

        public void seekTo(int progress) {
            if (totalDuration != 0) {
                float seekProgress = progress * totalDuration / 100;

                mediaPlayer.seekTo((int) seekProgress);//设置音乐的播放位置
            }
        }

        public boolean isPlaying() {
            if (mediaPlayer != null) {
                return mediaPlayer.isPlaying();
            }
            return false;
        }

        //播放下一首
        public void nextPlay() {

        }

        //
//        //播放上一首
        public void lastPlay() {

        }

        public void setVolume(float leftVolume, float rightVolume) {
            mediaPlayer.setVolume(leftVolume,rightVolume);
        }


    }

    @Override
    public void onDestroy() { //当服务被销毁就 销毁 mediaPlayer，释放资源
        super.onDestroy();
        LogsUtils.e("销毁 mediaPlaye");

    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogsUtils.e("销毁 onUnbind");
        cancelTimer();
        if (mediaPlayer == null) {
            if (mediaPlayer.isPlaying()) mediaPlayer.stop();//停止播放音乐
            mediaPlayer.release();//释放占用的资源
            mediaPlayer = null;//将player置为空
        }
        return super.onUnbind(intent);
    }
}
